package com.zaoniao.enstudy.domain.service;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelReader;
import com.alibaba.excel.read.metadata.ReadSheet;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.zaoniao.enstudy.domain.client.FileImportDataListener;
import com.zaoniao.enstudy.domain.entity.FileImportData;
import com.zaoniao.enstudy.domain.repository.ZaoWordExampleRepository;
import com.zaoniao.enstudy.domain.repository.ZaoWordRepository;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;

@Service
@Slf4j
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class FileService {
    /**
     * 单词表repository
     */
    private final ZaoWordRepository zaoWordRepository;
    /**
     * 单词例句表repository
     */
    private final ZaoWordExampleRepository zaoWordExampleRepository;

    public void importExcel(MultipartFile file) throws IOException {
        InputStream inputStream = file.getInputStream();
        // 读取excel
        try (ExcelReader excelReader = EasyExcel.read(inputStream,
                        FileImportData.class,
                        new FileImportDataListener(zaoWordRepository, zaoWordExampleRepository))
                .charset(StandardCharsets.UTF_8)
                .excelType(ExcelTypeEnum.XLSX)
                .build()) {
            // 构建一个sheet 这里可以指定名字或者no
            ReadSheet readSheet = EasyExcel.readSheet(0).build();
            // 读取一个sheet
            excelReader.read(readSheet);
        }

    }
}
